package test;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Rectangle;

public class AutoSizeLayout implements LayoutManager{
	int gapH=3;
	int gapW=5;
	float rate=1.666f;
	
	public void addLayoutComponent(String name, Component comp) {
		
	}

	public void layoutContainer(Container cn) {
		int count = cn.getComponentCount();
		
		int maxClumbCount=20;
		int rowCount=1;
		int clumbCount=1;
		int count2=0;
		float iW=0;
		float iH=0;
		for(clumbCount=1;clumbCount<maxClumbCount;clumbCount++){
			iW=cn.getWidth()/clumbCount;
			iH=iW/rate;
			
			rowCount=(int) (cn.getHeight()/iH);
			count2=clumbCount*rowCount;
			//System.out.println("HHH "+count+" "+count2);
			if(count2>=count){
				break;
			}
		}
		//System.out.println("EEEEEWWWWWWWW "+rowCount+" "+clumbCount+" "+count2);

		
		//System.out.println("UUUUUU "+iW+"  "+iH);
		
	    for (int i = 0 ; i < count ; i++) {
	    	 Component m = cn.getComponent(i);
	    	// System.out.println(m);
	    	 Rectangle rec=new Rectangle();
	    	 int cnum=i%clumbCount;
	    	 int rnum=i/clumbCount;
	    	 rec.x=(int) (cnum*iW);
	    	 rec.y=(int) (rnum*iH);
	    	 rec.width=(int) iW;
	    	 rec.height=(int) iH;
	    	 m.setBounds(rec);
	    	 
	    }
	}
	
	boolean rowCountAvail(Container cn,int count,int rowCount,float rate){
		boolean b=false;
		float iH=cn.getHeight()/rowCount;
		float iW=iH*rate;
		
		float iWH=iH*iW;
		
		int cWH=cn.getWidth()*cn.getHeight();
		int count2=(int) (cWH/iWH);
		//System.out.println("HHH "+count+" "+count2);
		if(count2>=count){
			b=true;
		}
		return b;
	}

	public Dimension minimumLayoutSize(Container parent) {
		return null;
	}

	public Dimension preferredLayoutSize(Container parent) {
		return null;
	}

	public void removeLayoutComponent(Component comp) {
		
	}
	
}
